﻿using System;
using System.Collections.Generic;
namespace GxFramework
{
    public class AssetBundleAssetLoader
    {
        int loaderMax = 3;

        List<AbAssetRequest> _waitingQueue = new List<AbAssetRequest>();
        List<AbAssetRequest> _loadingQueue = new List<AbAssetRequest>();
        List<AbAssetRequest> _loadedQueue = new List<AbAssetRequest>();
        Dictionary<AbAssetRequest, List<AbAssetRequest>> _requestToQueueMap = new Dictionary<AbAssetRequest, List<AbAssetRequest>>();

        public void Load(AbAssetRequest request)
        {
            if (request.status != AssetLoadStatus.Idle)
                return;
            _waitingQueue.Add(request);
            request.Wait();
            LoadInternal();
        }
        void LoadInternal()
        {
            while (_waitingQueue.Count != 0 && _loadingQueue.Count < loaderMax)
            {
                var req = _waitingQueue[0];
                _waitingQueue.RemoveAt(0);
                if (req.listenerCount > 0)
                {
                    _loadingQueue.Add(req);
                    _requestToQueueMap[req] = _loadingQueue;
                    req.Load();
                }
                else
                    req.Unload();
            }
        }
        public void Update()
        {
            int index = 0;
            int len = _loadingQueue.Count;
            for (int i = 0; i < len; ++i)
            {
                var req = _loadingQueue[i];
                req.Update();
                if (req.isDone)
                {
                    _loadedQueue.Add(req);
                }else
                {
                    if (index < i)
                    {
                        _loadingQueue[index] = req;
                    }
                    ++index;
                }
            }
            _loadingQueue.RemoveRange(index,len-index);

            len = _loadedQueue.Count;
            for (int i = 0; i < len; ++i)
            {
                var req = _loadedQueue[i];
                req.Invoke();
            }
            _loadedQueue.Clear();
        }
    }
}
